package org.ysling.litemall.wx.web;
/**
 *  Copyright (c) [ysling] [927069313@qq.com]
 *  [litemall-plus] is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *              http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 *  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.ysling.litemall.core.utils.JacksonUtil;
import org.ysling.litemall.core.utils.response.ResponseUtil;
import org.ysling.litemall.db.domain.LitemallMessage;
import org.ysling.litemall.db.service.LitemallMessageService;
import org.ysling.litemall.wx.annotation.LoginUser;

import java.util.*;

/**
 * 用户聊天列表
 */
@Slf4j
@RestController
@RequestMapping("/wx/message")
@Validated
public class WxMessageController {

    @Autowired
    private LitemallMessageService messageService;

    @GetMapping("list")
    public Object getMessageList(@LoginUser Integer userId){
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }

        //过滤重复数据 TODO 暂时只能获取给自己发过信息的列表
        HashMap<Integer, LitemallMessage> receiveMessageMap = new HashMap<>();
        List<LitemallMessage> receiveList = messageService.queryByReceiveUserId(userId);
        for (LitemallMessage message :receiveList) {
            receiveMessageMap.put(message.getSendUserId() , message);
        }

        //合并历史消息记录
        ArrayList<LitemallMessage> messageList = new ArrayList<>(receiveMessageMap.values());
        //历史消息排序
        messageList.sort(Comparator.comparing(LitemallMessage::getAddTime));
        //返回信息列表
        return ResponseUtil.okList(messageList);
    }

    @PostMapping("delete")
    public Object delete(@LoginUser Integer userId , @RequestBody String body){
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }
        Integer sendUserId = JacksonUtil.parseInteger(body, "sendUserId");
        if (sendUserId == null){
            return ResponseUtil.fail("删除失败，参数错误");
        }
        messageService.deleteMessage(userId , sendUserId);
        messageService.deleteMessage(sendUserId, userId);
        return ResponseUtil.ok();
    }

}
